const db = require('../utils/settings');
const fs = require('fs');
const pathLib = require('path');

function Users() {

}

Users.prototype.delUser = function (req, res, next) {
    db.query('SELECT * FROM user_table WHERE ID="' + req.query.id + '"', function (err, queryData) {
        if (err) {
            console.error(err);
            res.status(500).send({code: 500, msg: 'database error'});
        } else if (queryData.length == 0) {
            res.status(400).send({code: 400, msg: 'parameters error'});
        } else {
            // 删除服务器上的头像图片，然后删除数据库记录
            fs.unlink(queryData[0].pic_header.replace('\/files','public'), function (err) {
                if (err) {
                    console.error(err);
                    res.status(500).send({code:500,msg:'operate err'});
                } else {
                    db.query('DELETE FROM user_table WHERE ID="'+
                        req.query.id+'"',function (err,resultData) {
                        if(err){
                            console.error(err);
                            res.status(500).send({code: 500, msg: 'database error'});
                        }else{
                            res.redirect('/admin/users');
                        }
                    })
                }
            })
        }
    });
}

Users.prototype.modUser = function (req, res, next) {
    db.query('SELECT * FROM user_table',function (err,allData) {
        if (err) {
            console.error(err);
            res.status(500).send({code: 500, msg: 'database error'});
        } else {
            db.query('SELECT * FROM user_table WHERE ID="'+req.query.id+'"',function (err,modData) {
                if (err) {
                    console.error(err);
                    res.status(500).send({code: 500, msg: 'database error'});
                }else if(modData.length == 0){
                    res.status(400).send({code: 400, msg: 'parameters error'});
                }else {
                    res.render('users',{usersData:allData,modData:modData});
                }
            });
        }
    });
}

Users.prototype.searchUser = async function (req, res, next) {
    db.query('SELECT * FROM user_table', function (err, allUsersData) {
        if (err) {
            console.error(err);
            res.status(500).send({code: 500, msg: 'database error'});
        } else {
            res.render('users', {usersData: allUsersData});
        }
    });
}

Users.prototype.modified = function (req, res, next) {
    var username = req.body.username;
    var email = req.body.email;
    // req.files数据结构
    /*
    [ { fieldname: 'pic_header',
    originalname: 'mysql.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: './static/upload',
    filename: '30755a85dceed668fd4da998b6aabb52',
    path: 'static\\upload\\30755a85dceed668fd4da998b6aabb52',
    size: 10681 } ]
    */
    if(req.files.length>0){
        // pathLib.parse(req.files[0].originalname)
        /*
        { root: '',
          dir: '',
          base: 'logo1.png',
          ext: '.png',
          name: 'logo1' }
        */
        var ext = pathLib.parse(req.files[0].originalname).ext;
        var pic_header = '/files/upload/' + req.files[0].filename + ext;
    }

    //查看有没有新传来的头像，如果有，则删除，新建，如果没有，直接更新需要更新的内容
    if(req.files.length>0){
        //有修改头像，则进行原来头像的删除，再上传
        db.query('SELECT * FROM user_table WHERE ID="'+req.body.modified+'"',function (err,modData) {
            if (err) {
                console.error(err);
                res.status(500).send({code: 500, msg: 'database error'});
            }else if(modData.length == 0){
                res.status(400).send({code: 400, msg: 'parameters error'});
            }else{
                // fs.unlink删除文件操作
                // fs.unlink(path, [callback(err)])
                fs.unlink(modData[0].pic_header.replace('\/files','public'),function (err) {
                    if(err){
                        console.error(err);
                        res.status(500).send({code:500,msg:'operate error'});
                    }else{
                        //删除成功，开始对新的文件进行重命名
                        fs.rename(req.files[0].path, req.files[0].path + ext, function (err) {
                            if (err) {
                                console.error(err);
                                res.status(500).send({code: 500, msg: 'operate error'});
                            } else {
                                db.query('UPDATE user_table SET username="'+
                                    username+'",email="' + email + '",pic_header="' +
                                    pic_header + '" WHERE ID="'+req.body.modified+'"',function (err,data) {
                                    if (err) {
                                        console.error(err);
                                        res.status(500).send({code: 500, msg: 'database error'});
                                    }else{
                                        res.redirect('/admin/users');
                                    }
                                });
                            }
                        });
                    }
                })
            }
        })
    }else{
        db.query('UPDATE user_table SET username="'+username+'",email="' + email + '" WHERE ID="'+
            req.body.modified+'"',function (err,data) {
            if (err) {
                console.error(err);
                res.status(500).send({code: 500, msg: 'database error'});
            }else{
                res.redirect('/admin/users');
            }
        });
    }
}

Users.prototype.addUser = function (req, res, next) {
    var username = req.body.username;
    var email = req.body.email;
    if(req.files.length>0){
        var ext = pathLib.parse(req.files[0].originalname).ext;
        var pic_header = '/files/upload/' + req.files[0].filename + ext;
    }

    // 存储头像文件到服务器static/upload，然后将新增记录插入数据库
    // fs.rename修改文件名称，可更改文件的存放路径。
    // fs.rename(oldPath, newPath, [callback(err)])
    fs.rename(req.files[0].path, req.files[0].path + ext, function (err) {
        if (err) {
            console.error(err);
            res.status(500).send({code: 500, msg: 'data error'});
        } else {
            db.query('INSERT INTO user_table (username,email,pic_header) VALUE("' + username + '","' +
                email + '","' + pic_header + '")', function (err, resultData) {
                if (err) {
                    console.error(err);
                    res.status(500).send({code: 500, msg: 'database error'});
                } else {
                    res.redirect('/admin/users');
                }
            });
        }
    });
}

module.exports = new Users();